package com.iwhalecloud.bss.kite.cucc.service.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Des3Util {
    /**
     * 加密
     * 
     * @param data
     * @param keyHex
     * @param ivHex
     * @return
     * @throws Exception
     */
    public static String desEncrypt(byte[] data, String keyHex, String ivHex) throws Exception {
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

        SecretKey secretKey = new SecretKeySpec(hex2ba(keyHex), "DESede");
        IvParameterSpec iv = new IvParameterSpec(hex2ba(ivHex));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        return encryptBASE64(cipher.doFinal(data));
    }

    /**
     * 解密
     * 
     * @param data
     * @param keyHex
     * @param ivHex
     * @return
     * @throws Exception
     */
    public static String desDecrypt(String data, String keyHex, String ivHex) throws Exception {
        byte[] dataByte = decryptBASE64(data);
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); // DESede/CBC/PKCS5Padding

        SecretKey secretKey = new SecretKeySpec(hex2ba(keyHex), "DESede");
        IvParameterSpec iv = new IvParameterSpec(hex2ba(ivHex));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

        return new String(cipher.doFinal(dataByte), "GBK");
    }

    /**
     * @param hexString
     * @return
     */
    public static byte[] hex2ba(String hexString) {
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }

    /**
     * BASE64解密
     * 
     * @param key = 需要解密的密码字符串
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * BASE64加密
     * 
     * @param key = 需要加密的字符数组
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }
}
